<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required/>
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required/>
      </div>
      <button type="submit">登录</button>
      <router-link to="/register">没有账号？注册</router-link>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    handleLogin() {
      console.log('handleLogin 方法被调用'); // 添加日志
      console.log('用户名:', this.username);
      console.log('密码:', this.password);
      // 在此处添加实际的登录请求逻辑
      axios.post('http://localhost:4000/api/login', {username: this.username, password: this.password})
          .then(response => {
            console.log('登录成功:', response.data); // 添加日志
            localStorage.setItem('userToken', response.data.token); // 将 token 存储到 localStorage
            localStorage.setItem('username', this.username); // 将用户名存储到 localStorage
            localStorage.setItem('loginTimestamp', Date.now()); // 将登录时间戳存储到 localStorage
            this.$router.push('/dashboard'); // 导航到主界面
            // 处理成功的登录逻辑，例如存储令牌
          })
          .catch(error => {
            console.error('登录失败:', error); // 添加日志
            // 处理登录失败逻辑
          });
    }
  }
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

h2 {
  text-align: center;
}

form div {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #00914D;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #007A3F;
}
</style>